//监控统计
var MonitorStatisc = function() {
    this.id = 'MonitorStatisc';
    this._data = this.getData();
    this._container = $('.monitotleResContainer');
    this.config = Project_ParamConfig.monitorStatiscConfig;
};
MonitorStatisc.prototype.start = function() {
    var html = this.getResultHTML();
    this._container.html(html);
    this._initResEvts();
    if (this._data.realtimeChk && this._data.historyChk) {
        this._container.find(".realTime-secondFilter").css("display", "block");
        this._container.find(".histroy-secondFilter").css("display", "none");
    } else if (!this._data.realtimeChk) {
        this._container.find(".result").css("display", "none").end().find(".result-history").css("display", "block");
    }
    this._container.find(".nav-titleNav>li.active>a").click();
};
MonitorStatisc.prototype.getResultHTML = function() {
    var html = [];
    html.push(this.getTitleNavHTML());
    html.push(this.getSecondFilterHtml());
    html.push('<div class="result result-realTime-0"></div>');
    html.push('<div class="result result-realTime-1"></div>');
    html.push('<div class="result result-history">正在统计中...</div>');
    return html.join("");
};
MonitorStatisc.prototype._initResEvts = function() {
    var $container = this._container;
    $container.find(".histroy-secondFilter input.startTime").val(this._data.startTimeWdate);
    $container.find(".histroy-secondFilter input.endTime").val(this._data.endTimeWdate);
    $container.find(".nav-titleNav>li>a").on("click", { context: this }, this._firstTitleEvt);
    $container.find(".nav-secondNav>li>a").on("click", { context: this }, this._secondFilterEvt);
    $container.find(".histroy-secondFilter button").on("click", { context: this }, this._historySecEvt);
    $container.find(".histroy-secondFilter input").on("click", { context: this }, this._onFocus);
};
MonitorStatisc.prototype._firstTitleEvt = function(e) {
    var self = e.data.context,
        type = $(this).data("info"),
        $container = self._container;
    $(this).parent().addClass("active").siblings().removeClass("active");
    if (type == "realTime") {
        $container.find(".realTime-secondFilter").css("display", "block");
        $container.find(".histroy-secondFilter").css("display", "none");
        $container.find(".nav-secondNav>li:first-child>a").click();
    } else if (type == "history") {
        $container.find(".realTime-secondFilter").css("display", "none");
        $container.find(".histroy-secondFilter").css("display", "block");
        $container.find(".result").css("display", "none").end().find(".result-history").css("display", "block");
        $container.find(".histroy-secondFilter button").click();
    }
};
MonitorStatisc.prototype._secondFilterEvt = function(e) {
    var self = e.data.context,
        type = $(this).data("info"),
        $container = self._container;
    $(this).parent().addClass("active").siblings().removeClass("active");
    //数量统计
    if (type == "realTime-0") {
        $container.find(".result").css("display", "none").end().find(".result-realTime-0").css("display", "block");
        //数量统计
        if (self._timer) {
            clearInterval(self._timer);
            self._timer = null;
        }
        //首次
        var targets = self.getTargets();
        if (targets.length) {
            self.realtimeCountRes(targets);
        }
        //轮询
        self._timer = setInterval(function() {
            var targets = self.getTargets();
            if (targets.length) {
                self.realtimeCountRes(targets);
            }
        }, self.config.updateTime);
        //目标列表
    } else if (type == "realTime-1") {
        $container.find(".result").css("display", "none").end().find(".result-realTime-1").css("display", "block");
        //目标列表
        if (self._timer) {
            clearInterval(self._timer);
            self._timer = null;
        }
        //首次
        var targets = self.getTargets();
        if (targets.length) {
            self.realtimeAreaRes(targets);
        }
        //轮询
        self._timer = setInterval(function() {
            var targets = self.getTargets();
            if (targets.length) {
                self.realtimeAreaRes(targets);
            }
        }, self.config.updateTime);
    }
};
MonitorStatisc.prototype.realtimeCountRes = function(data) {
    //js linq -start
    var gbco = data.groupBy('countryOrig');
    var result = [];
    for (var i = 0, len = gbco.length; i < len; i++) {
        var obj = {};
        obj.co = gbco[i].key.trim() || '未知';
        var value = gbco[i].value;
        var gbval = value.groupBy('shiptype');
        for (var j = 0, lenj = gbval.length; j < lenj; j++) {
            var gj = gbval[j];
            if (gj.key === '货船') {
                obj.tc1 = gj.value.length;
            } else if (gj.key === '搜救船') {
                obj.tc2 = gj.value.length;
            } else if (gj.key === '油轮') {
                obj.tc3 = gj.value.length;
            } else if (gj.key === '拖船') {
                obj.tc4 = gj.value.length;
            } else if (gj.key === '渔船') {
                obj.tc5 = gj.value.length;
            } else if (gj.key === '客船') {
                obj.tc6 = gj.value.length;
            } else if (gj.key === '军事船') {
                obj.tc7 = gj.value.length;
            } else if (gj.key === '其他') {
                obj.tc100 = gj.value.length;
            }
        }
        if (!obj.tc1) obj.tc1 = 0;
        if (!obj.tc2) obj.tc2 = 0;
        if (!obj.tc3) obj.tc3 = 0;
        if (!obj.tc4) obj.tc4 = 0;
        if (!obj.tc5) obj.tc5 = 0;
        if (!obj.tc6) obj.tc6 = 0;
        if (!obj.tc7) obj.tc7 = 0;
        if (!obj.tc100) obj.tc100 = 0;
        result.push(obj);
    }
    ///js linq -end
    var $container = this._container;
    var sumCount = data.length;
    var list = result;
    var html = [];
    html.push('<p>实时船舶总数：' + sumCount + '艘</p>');
    html.push('<table>');
    html.push('<thead><tr><th>国别</th><th>货船</th><th>搜救船</th><th>油轮</th><th>拖船</th><th>渔船</th><th>客船</th><th>军事船</th><th>其他</th></tr></thead>');
    html.push('<tbody>');
    for (var i = 0, len = list.length; i < len; i++) {
        var eobj = list[i];
        html.push('<tr>');
        html.push('<td title="' + eobj.co + '">' + eobj.co + '</td>');
        html.push('<td>' + eobj.tc1 + '</td>');
        html.push('<td>' + eobj.tc2 + '</td>');
        html.push('<td>' + eobj.tc3 + '</td>');
        html.push('<td>' + eobj.tc4 + '</td>');
        html.push('<td>' + eobj.tc5 + '</td>');
        html.push('<td>' + eobj.tc6 + '</td>');
        html.push('<td>' + eobj.tc7 + '</td>');
        html.push('<td>' + eobj.tc100 + '</td>');
        html.push('</tr>');
        if (i < len - 1) {
            html.push('<tr class="splitTr"><td colspan="8">&nbsp</td></tr>');
        }
    }
    html.push('</tbody>');
    html.push('</table>');
    html = html.join("");
    $container.find(".result-realTime-0").html(html);
};
MonitorStatisc.prototype.realtimeAreaRes = function(data) {
    var $container = this._container;
    var list = data;
    var html = [];
    html.push('<p>实时船舶总数：' + data.length + '艘</p>');
    html.push('<table>');
    html.push('<thead><tr>');
    html.push('<th>批号</th>');
    html.push('<th>模式</th>');
    html.push('<th>船名</th>');
    html.push('<th>国家/地区</th>');
    html.push('<th>船舶类型</th>');
    html.push('<th>经度</th>');
    html.push('<th>纬度</th>');
    html.push('<th>时间</th>');
    html.push('<th>船速</th>');
    html.push('<th>航向</th>');
    html.push('<th>信息来源</th>');
    html.push('<th>信息类型</th>');
    html.push('</tr></thead>');
    html.push('<tbody>');
    for (var i = 0, len = list.length; i < len; i++) {
        var obj = list[i];
        var lat = obj.lat;
        var lng = obj.lon;
        var time = obj.time;
        var xxlx = obj.infotype;
        var xxly = obj.infosrc;
        var mode = obj.mode === 0 ? '融合模式' : '原始模式';
        html.push('<tr>');
        html.push('<td>' + obj.id + '</td>');
        html.push('<td>' + mode + '</td>');
        html.push('<td>' + obj.shipname + '</td>');
        html.push('<td>' + obj.countryOrig + '</td>');
        html.push('<td>' + obj.shiptype + '</td>');
        html.push('<td title="' + lng + '">' + lng + '</td>');
        html.push('<td title="' + lat + '">' + lat + '</td>');
        html.push('<td title="' + time + '">' + time + '</td>');
        html.push('<td>' + obj.speed + ' 节</td>');
        html.push('<td>' + obj.dir + '°</td>');
        html.push('<td>' + xxly + '</td>');
        html.push('<td>' + xxlx + '</td>');
        html.push('</tr>');
        if (i < len - 1) {
            html.push('<tr class="splitTr"><td colspan="8">&nbsp</td></tr>');
        }
    }
    html.push('</tbody>');
    html.push('</table>');
    html = html.join("");
    $container.find(".result-realTime-1").html(html);
};
MonitorStatisc.prototype._historySecEvt = function(e) {
    var self = e.data.context;
    var $container = self._container;
    var $msg = $container.find(".histroy-secondFilter .msg");
    var startTime = $container.find(".histroy-secondFilter input.startTime").val();
    var endTime = $container.find(".histroy-secondFilter input.endTime").val();
    var checkRes = self.checkStrartEndTime(startTime + ":00", endTime + ":00", 7);
    $msg.text('');
    if (!checkRes.result) {
        $msg.text(checkRes.msg);
        return;
    }
    var data = {};
    var url = self.config.realtimeAreaUrl;
    var areaPoint = self._data.areaPoint;
    if(self._data.areaType === 'circle') {
        url = self.config.realtimeAreaUrl_Circle;
        data.cirlon = areaPoint.cirlon;
        data.cirlat = areaPoint.cirlat;
        data.radius = areaPoint.radius;
    } else if(self._data.areaType === 'polygon') {
        url = self.config.realtimeAreaUrl_Polygon;
        data.lonStrArr = areaPoint.lonStrArr;
        data.latStrArr = areaPoint.lonStrArr;
    } else if(self._data.areaType === 'rect'){
        url = self.config.realtimeAreaUrl;
        data.ldlon = areaPoint.sw.lng; //左下经度
        data.ldlat = areaPoint.sw.lat; //左下纬度
        data.rulon = areaPoint.ne.lng;
        data.rulat = areaPoint.ne.lat;
    }else if(self._data.areaType === 'sector'){
        url = self.config.realtimeAreaUrl_Sector;
        data.lon = areaPoint.lon;
        data.lat = areaPoint.lat;
        data.radius = areaPoint.radius;
        data.radsmal = areaPoint.radsmal;
        data.startDeg = areaPoint.startDeg;
        data.endDeg = areaPoint.endDeg;
        data.limit = areaPoint.limit;
    }
    data.mode = self._data.mode;
    data.startTime = self.getCusUnixTime(startTime + ":00");
    data.endTime = self.getCusUnixTime(endTime + ":00");
    self.histroySendAjax(url, data);
};
MonitorStatisc.prototype.histroySendAjax = function(url, data) {
    // var url = this.config.realtimeAreaUrl_hive;
    var self = this;
    $.post(url, data, function(res) {
        if (res.state !== 1) {
            return;
        }
        self.renderHisResTable(res);
    }, 'json');
};
MonitorStatisc.prototype.renderHisResTable = function(data) {
    var $container = this._container.find(".result-history");
    var enterList = data.msg.shipList[0].enterareacountlist;
    var outList = data.msg.shipList[1].leaveareacountlist;
    var enterCount = data.msg.shipList[0].enterareacount;
    var outCount = data.msg.shipList[1].leaveareacount;
    var html = [];
    html.push('<div class="stasticTableDiv">');
    html.push('<p>船舶驶入总数：' + enterCount + '艘</p>');
    html.push('<div class="stastic_table_enter">');
    html.push('<table>');
    html.push('<thead><tr><th>国别</th><th>货船</th><th>搜救船</th><th>油轮</th><th>拖船</th><th>渔船</th><th>客船</th><th>军事船</th><th>其他</th></tr></thead>');
    html.push('<tbody>');
    for (var i = 0, len = enterList.length; i < len; i++) {
        var eobj = enterList[i];
        html.push('<tr>');
        html.push('<td>' + (eobj.co.replace(/@/g, '') || '未知') + '</td>');
        html.push('<td>' + eobj.tc1 + '</td>');
        html.push('<td>' + eobj.tc2 + '</td>');
        html.push('<td>' + eobj.tc3 + '</td>');
        html.push('<td>' + eobj.tc6 + '</td>');
        html.push('<td>' + eobj.tc5 + '</td>');
        html.push('<td>' + eobj.tc7 + '</td>');
        html.push('<td>' + eobj.tc8 + '</td>');
        html.push('<td>' + eobj.tc10000 + '</td>');
        html.push('</tr>');
        if (i < len - 1) {
            html.push('<tr class="splitTr"><td colspan="8">&nbsp</td></tr>');
        }
    }
    html.push('</tbody>');
    html.push('</table>');
    html.push('</div>');
    html.push('<p>船舶驶离总数：' + outCount + '艘</p>');
    html.push('<div class="stastic_table_out">');
    html.push('<table>');
    html.push('<thead><tr><th>国别</th><th>货船</th><th>搜救船</th><th>油轮</th><th>拖船</th><th>渔船</th><th>客船</th><th>军事船</th><th>其他</th></tr></thead>');
    html.push('<tbody>');
    for (var i = 0, len = outList.length; i < len; i++) {
        var otbj = outList[i];
        html.push('<tr>');
        html.push('<td>' + (otbj.co.replace(/@/g, '') || '未知') + '</td>');
        html.push('<td>' + otbj.tc1 + '</td>');
        html.push('<td>' + otbj.tc2 + '</td>');
        html.push('<td>' + otbj.tc3 + '</td>');
        html.push('<td>' + otbj.tc6 + '</td>');
        html.push('<td>' + otbj.tc5 + '</td>');
        html.push('<td>' + otbj.tc7 + '</td>');
        html.push('<td>' + otbj.tc8 + '</td>');
        html.push('<td>' + otbj.tc10000 + '</td>');
        html.push('</tr>');
        if (i < len - 1) {
            html.push('<tr class="splitTr"><td colspan="8">&nbsp</td></tr>');
        }
    }
    html.push('</tbody>');
    html.push('</table>');
    html.push('</div>');
    html.push('</div>');
    html = html.join("");
    $container.html(html);
};
MonitorStatisc.prototype._onFocus = function(e) {
    var self = e.data.context;
    var obj = {
        readOnly: true,
        dateFmt: 'yyyy-MM-dd HH:mm',
        isShowClear: false,
        minDate: self._data.startTimeWdate,
        maxDate: self._data.endTimeWdate
    };
    WdatePicker(obj);
};
MonitorStatisc.prototype.getTitleNavHTML = function() {
    var html = '';
    html += '<ul  class="nav nav-titleNav">';
    if (this._data.realtimeChk === false) {
        html += '<li class="active"><a href="#" data-info="history">历史进出统计</a></li>';
    } else if (this._data.historyChk === false) {
        html += '<li class="active"><a href="#" data-info="realTime">实时船舶数量</a></li>';
    } else {
        html += '<li class="active"><a href="#" data-info="realTime">实时船舶数量</a></li>';
        html += '<li><a href="#" data-info="history">历史进出统计</a></li>';
    }
    html += '</ul>';
    return html;
};
MonitorStatisc.prototype.getSecondFilterHtml = function() {
    var realTimeHTML = '',
        historyHTML = '';
    realTimeHTML += '<div class="realTime-secondFilter">';
    realTimeHTML += '<ul class="nav nav-secondNav">';
    realTimeHTML += '<li class="active"><a href="#" data-info="realTime-0">数量统计</a></li>';
    realTimeHTML += '<li><a href="#" data-info="realTime-1">目标列表</a></li>';
    realTimeHTML += '</ul>';
    realTimeHTML += '</div>';
    historyHTML += '<div class="histroy-secondFilter">';
    historyHTML += '<label>时间范围：<input class="startTime Wdate" type="text"><span>&nbsp&nbsp</span>至<span>&nbsp&nbsp</span><input class="endTime Wdate" type="text"><label><span>&nbsp&nbsp</span>';
    historyHTML += '<button type="button">确定</button>';
    historyHTML += '<label class="msg"></label>';
    historyHTML += '</div>';
    if (this._data.realtimeChk === false) {
        return historyHTML;
    } else if (this._data.historyChk === false) {
        return realTimeHTML;
    } else {
        return realTimeHTML + historyHTML;
    }
};
MonitorStatisc.prototype.getDateFromformatFull = function(datestring) {
    var ary1 = datestring.split(" ");
    var arydate = ary1[0].split("-");
    var arytime = ary1[1].split(":");
    var y = parseInt(arydate[0]);
    var mm = parseInt(arydate[1]);
    var d = parseInt(arydate[2]);
    var h = parseInt(arytime[0]);
    var m = parseInt(arytime[1]);
    var s = parseInt(arytime[2]);
    var retdate = new Date(y, mm, d, h, m, s);
    return retdate;
};
MonitorStatisc.prototype.checkStrartEndTime = function(startsj, endsj, range) {
    var startsjnew = this.getDateFromformatFull(startsj);
    var endsjnew = this.getDateFromformatFull(endsj);
    startsjnew = startsjnew.valueOf();
    endsjnew = endsjnew.valueOf();
    if (startsjnew > endsjnew) {
        return { result: false, msg: "开始时间不能晚于结束时间！" };
    } else {
        var sjc = range * 24 * 60 * 60 * 1000;
        var sjsjc = endsjnew - startsjnew;
        if (sjsjc > sjc) {
            var res = (range >= 3 * 30 ? "三个月" : range + "天");
            return { result: false, msg: "时间范围不能超过" + res + "！" };
        }
    }
    return { result: true, msg: "" };;
};
MonitorStatisc.prototype.getCusUnixTime = function(sjstr) {
    var sjsplit = sjstr.split(" ");
    var ymd = sjsplit[0].split("-");
    var hms = sjsplit[1].split(":");
    var year = parseInt(ymd[0]);
    var month = parseInt(ymd[1]) > 0 ? parseInt(ymd[1]) - 1 : 0;
    var day = parseInt(ymd[2]);
    var hour = parseInt(hms[0]);
    var minutes = parseInt(hms[1]);
    var seconds = parseInt(hms[2]);
    var d = new Date(year, month, day, hour, minutes, seconds);
    return d.valueOf() / 1000;
};
MonitorStatisc.prototype.getTargets = function() {
    var value = window.localStorage.getItem(this.id);
    if (value !== null) {
        try {
            value = JSON.parse(value);
        } catch (e) {
            return value;
        }
    }
    return value;
};
MonitorStatisc.prototype.getData = function() {
    var value = window.localStorage.getItem(this.id + '_data');
    if (value !== null) {
        try {
            value = JSON.parse(value);
        } catch (e) {
            return value;
        }
    }
    return value;
};
